package com.kzd.gtgame.main.mine

import android.content.Intent
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.LifecycleOwner
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.setOnClickAntiShakeListener
import com.kzd.gtgame.custom.setTransitionStatus
import com.kzd.gtgame.entity.Feedback
import com.kzd.gtgame.jetpack.vm.MineViewModel
import com.kzd.gtgame.main.KEY_GAME_DETAILS_ID
import com.kzd.gtgame.main.KEY_GAME_DETAILS_TITLE
import com.kzd.gtgame.main.game.GameRankingFragment
import com.kzd.gtgame.main.home.adapter.ImageSelectAdapter
import com.kzd.gtgame.main.mine.adapter.FeedbackTypeAdapter
import com.kzd.gtgame.main.popup.GameFeedbackPopup
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg

import com.module.lemlin.owner.OwnerViewModeFragment
import com.zhihu.matisse.Matisse
import kotlinx.android.synthetic.main.activity_bargain_sell.*
import kotlinx.android.synthetic.main.fragment_feedback_game.*
import java.lang.StringBuilder


class FeedbackGameFragment : OwnerViewModeFragment<MineViewModel>() {

    companion object {
        fun newInstance(gName: String? = null, gid: String? = null): FeedbackGameFragment {
            val bundle: Bundle = Bundle().apply {
                putString(KEY_GAME_DETAILS_TITLE, gName)
                putString(KEY_GAME_DETAILS_ID, gid)
            }
            return FeedbackGameFragment().apply {
                arguments = bundle
            }
        }
    }


    private val mGameName: String?
        get() = arguments?.getString(KEY_GAME_DETAILS_TITLE, null)

    private val mGameId: String?
        get() = arguments?.getString(KEY_GAME_DETAILS_ID, null)

    private var mImages: MutableList<String> = mutableListOf()
    private val mImageSelectAdapter = ImageSelectAdapter()
    private val mFeedbackTypeAdapter = FeedbackTypeAdapter()

    private val mFeedback: Feedback = Feedback(type = "0")

    private val mGameFeedbackPopup: GameFeedbackPopup by lazy {
        GameFeedbackPopup(requireContext()) { _, game ->
            mGameFeedbackPopup.dismiss()
            tvFeedbackGameName.text = game.name
            mFeedback.apply {
                game_id = game.id
            }
        }
    }

    override fun viewModel(): MineViewModel {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.fragment_feedback_game

    override fun initView() {

        tvFeedbackGameModel.text = StringBuilder().append(Build.BRAND)
            .append("\n").append(Build.MODEL)

        tvFeedbackGameName.text = mGameName

        mFeedback.apply {
            mobile_model = tvFeedbackGameModel.text.toString()
            game_id = mGameId
        }

        rvFeedbackGameTypeBody.adapter = mFeedbackTypeAdapter

        rvFeedbackGameImageBody.adapter = mImageSelectAdapter.apply {
            setNewInstance(mutableListOf(R.mipmap.photo_add_icon))
        }
        mImageSelectAdapter.setOnItemClickListener { _, _, position ->
            if (position != 0) {
                return@setOnItemClickListener
            }
            viewModel.userMatisse(fragment = this, maxSelectable = 7)
        }

        tvFeedbackGameName.setOnClickAntiShakeListener {
            viewModel.mineFeedbackGame()
        }

        tvFeedbackGameSubmit.setOnClickAntiShakeListener {
            when {
                tvFeedbackGameName.text.isNullOrEmpty() -> {
                    toast("请选择游戏")
                    return@setOnClickAntiShakeListener
                }
                tvFeedbackGameWx.text.isNullOrEmpty() -> {
                    toast("请输入微信号")
                    return@setOnClickAntiShakeListener
                }
                tvFeedbackGamePhone.text.isNullOrEmpty() -> {
                    toast("请输入联系电话")
                    return@setOnClickAntiShakeListener
                }
                mFeedbackTypeAdapter.data.filter { it.isSelect }.isNullOrEmpty() -> {
                    toast("请选择举报类型")
                    return@setOnClickAntiShakeListener
                }
                tvFeedbackGameContent.text.isNullOrEmpty() -> {
                    toast("请输入内容")
                    return@setOnClickAntiShakeListener
                }
                mImages.isNullOrEmpty() -> {
                    toast("请选择图片")
                    return@setOnClickAntiShakeListener
                }
                else -> {
                    val feedbackType = mFeedbackTypeAdapter.data.filter { it.isSelect }
                    val classify = StringBuilder()
                    feedbackType.forEach {
                        classify.append(it.id).append(",")
                    }
                    if (classify.isNotEmpty()) {
                        mFeedback.apply {
                            this.classify = classify.substring(0, classify.length - 1).toString()
                        }
                    }
                    viewModel.userUpload(images = mImages)
                }
            }
        }

        tvFeedbackGameWx.addTextChangedListener {
            mFeedback.apply { qq = it?.toString() }
        }
        tvFeedbackGamePhone.addTextChangedListener {
            mFeedback.apply { mobile = it?.toString() }
        }
        tvFeedbackGameContent.addTextChangedListener {
            mFeedback.apply { content = it?.toString() }
        }

    }

    override fun initData() {
        viewModel.mineFeedbackType()
    }

    override fun initViewMode() {
        viewModel.feedbackTypeLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            mFeedbackTypeAdapter.setNewInstance(data)
        })

        viewModel.gameFeedbackLiveData.observe(viewLifecycleOwner, { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
            if (response.status != Status.SUCCESS) {
                return@observe
            }
            val data = response.data?.data
                ?: return@observe
            mGameFeedbackPopup.fillDataGameFeedback(data)
                .showPopupWindow()
        })

        viewModel.mineFeedbackLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            toast(response.data?.message)
            requireActivity().finish()
        })

        viewModel.userUploadLiveData.observe(this as LifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            if (data.size == 0)
                return@observe
            val images = StringBuilder()
            data.forEach {
                images.append(it).append(",")
            }
            if (images.isNotEmpty()) {
                mFeedback.apply {
                    this.imgs = images.substring(0, images.length - 1).toString()
                }
            }
            viewModel.mineFeedback(mFeedback)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 100 && resultCode == AppCompatActivity.RESULT_OK) {
            val pathList: MutableList<String> = Matisse.obtainPathResult(data).toMutableList()
            if (pathList.size == 0)
                return
            val images: MutableList<Any> = mutableListOf()
            images.add(R.mipmap.photo_add_icon)
            pathList.forEach {
                images.add(it)
            }
            mImageSelectAdapter.setNewInstance(images)
            mImages.clear()
            mImages.addAll(pathList)
        }
    }

}